package base64util

import (
	"bytes"
	"encoding/base64"
	"image"
	"image/png"
	"os"
	"path/filepath"
	"strings"

	"gitee.com/tomatomeatman/golang-repository/bricks/model/emity"
)

// Base64转换为PNG图片
func Base64ToPng(base64Data, savePath string) *emity.MsgEmity {
	iSt := strings.Index(base64Data, ",")
	if iSt > 0 { //清除前缀
		base64Data = base64Data[iSt+1:]
	}

	// 解码Base64字符串为字节流
	decodedBytes, err := base64.StdEncoding.DecodeString(base64Data)
	if err != nil {
		return emity.MsgEmity{}.Err(1001, "无法解码base64:", err)
	}

	// 将解码后的字节流转换为image.Image接口实例
	img, _, err := image.Decode(bytes.NewReader(decodedBytes))
	if err != nil {
		return emity.MsgEmity{}.Err(1002, "解码图像失败:", err)
	}

	dirPath := filepath.Dir(savePath)

	// 检查并创建目录（如果不存在的话）
	if err := os.MkdirAll(dirPath, 0755); err != nil {
		return emity.MsgEmity{}.Err(1003, "创建输出文件夹失败:", err)
	}

	outFile, err := os.Create(savePath) // 创建一个新的文件来保存图片
	if err != nil {
		return emity.MsgEmity{}.Err(1004, "创建输出文件失败:", err)
	}
	defer outFile.Close()

	// 使用png格式编码器将图像写入文件
	err = png.Encode(outFile, img)
	if err != nil {
		return emity.MsgEmity{}.Err(1005, "未能将图像编码为PNG:", err)
	}

	return emity.MsgEmity{}.Success(1999, "图片保存成功！")
}
